package com.lsk.task;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.api.AccessToken;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.cache.IAccessTokenCache;
import com.jfinal.weixin.sdk.kit.ParaMap;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import com.jfinal.weixin.sdk.utils.RetryUtils;
import com.lsk.util.Syslog;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * 刷新微信公众号token
 * Created by Administrator on 2018/8/2 0002.
 */
public class RefreshWxaToken {
    Cache cache= Redis.use();
    private static String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
    private static Map<String, String> queryParas=null;
    public RefreshWxaToken(){
        String sql="SELECT *from weixin_public_account_info where type=1 GROUP BY appId";
        List<Record> recordList= Db.find(sql);
        for (int i=0;i<recordList.size();i++){
            try {
                Record tempRecord=recordList.get(i);
                String appId=tempRecord.getStr("appId");
                String appsecret=tempRecord.getStr("appSecret");
                String orgId=tempRecord.getStr("shopId");
                final Map<String, String> queryParas = ParaMap.create("appid", appId).put("secret", appsecret).getData();
                RefreshWxaToken.queryParas=queryParas;
                AccessToken result = (AccessToken) RetryUtils.retryOnException(3, new Callable<AccessToken>() {
                    public AccessToken call() throws Exception {
                        String json = HttpUtils.get(RefreshWxaToken.url, RefreshWxaToken.queryParas);
                        return new AccessToken(json);
                    }
                });
                String token=result.getAccessToken();
                String rule="wxaToken";
                cache.set(rule+appId,token);
                cache.set(rule+orgId,token);

                IAccessTokenCache accessTokenCache = ApiConfigKit.getAccessTokenCache();
                accessTokenCache.set(appId, result.getCacheJson());

                Syslog.info("获取到的token信息" +result.getJson());

            }catch (Exception e){
                Syslog.error(e);
            }finally {
                RefreshWxaToken.queryParas=null;
            }
        }
    }
}
